class ClientsController < ApplicationController
  before_filter :validate_client , :except => [ :home , :test_create , :create ]

  def home ; render :text => 'hello' ; end ;

  def test_create
    room   = client_params[:room]
    nicks  = client_params[:nicks]
    client = Client.find_by_room (URI.escape room)

    client.delete if client.present? && room == TEST_ROOM && nicks != TEST_DUPS_NICKS

    create
  end






def create_dummies # DEBUG
  tokens = params[:room].split ' '
  peer   = Client.create { :room  => "OtherGrid #{tokens[1]} #{tokens[2]} #{Time.now}" ,
                           :nicks => 'OtherGridNick1,OtherGridNick2'                   ,
                           :type  => 'SimClient'                                       }
  @client.peers << peer.id unless peer.new_record?
  peer   = Client.create { :room  => "AnotherGrid #{tokens[1]} #{tokens[2]} #{Time.now}" ,
                           :nicks => 'AnotherGridNick1,AnotherGridNick2'                 ,
                           :type  => 'SimClient'                                         }
  @client.peers << peer.id unless peer.new_record?
end





  def create
    begin
      @client = Client.create client_params
      secret  = @client.secret

create_dummies unless @client.subscriptions.count > 0 # DEBUG

    rescue ActiveRecord::RecordNotUnique
      secret = TEST_DUPS_RESP
    end

    fail and return if @client.present? && @client.new_record?

    render :json => { :secret => secret }
  end

  def message
    message = @client.messages.create message_params

    fail and return if message.new_record?

    @client.messages.first.delete

    @client.peers.each { | peer | peer.subscriptions << message }

    render :json => { :message => 'created' }
  end

  def messages
    ts       = (DateTime.parse params[:ts]) + 0.9.seconds
#     messages = (@client.messages.where "created_at > ?" , ts) # TODO: collate other clients messages
    messages = (@client.subscriptions.where "created_at > ?" , ts)

    render :json => { :messages => messages }
  end

  def fail
    render :text => 'NFG' , :status => 420
  end


private

  def authenticate_client
    params  = client_auth_params
    room    = params[:room  ]
    secret  = params[:secret]
    client  = Client.find_by_room (URI.escape room)
    @client = client if client.present? && client.secret == secret
  end

  def validate_client
    fail and return unless authenticate_client
  end

  def client_params
    client = params.require :client
    { :room  => (client.require :room ) ,
      :nicks => (client.require :nicks) ,
      :type  => (client.require :type ) }
  end

  def message_params
    client = params.require :client
    { :nick => (client.require :nick) ,
      :text => (client.require :text) }
  end

  def client_auth_params
    { :room    => (params.require :room  )                  ,
      :secret  => (params.require :client).require(:secret) }
  end
end
